<template>
  <div class="hospital-system">
    <!-- 顶部导航栏 -->
    <van-nav-bar
        title="健康管理"
        fixed
        placeholder
        safe-area-inset-top
        :border="false"
        :style="{ backgroundColor: '#1989fa', color: 'white', zIndex: 101 }"

    />
    <!--        left-arrow-->
    <!--        @click-left="handleGoBack"-->
    <!-- 选项卡导航 -->
    <van-tabs
        v-model="activeTab"
        animated
        background="#1989fa"
        color="#fff"
        title-active-color="#fff"
        title-inactive-color="rgba(255, 255, 255, 0.7)"
        :style="{
        position: 'fixed',
        top: '46px',
        zIndex: 100,
        width: '100%',
        height: 'calc(100vh - 46px)'
      }"
    >
      <!-- 健康档案标签页 -->
      <van-tab title="健康档案">
        <div class="scroll-container">
          <div class="selector-trigger" @click="toggleSelector">
            <span>切换档案：{{ currentPatient.name }}</span>
            <van-icon
                name="arrow-down"
                size="16px"
                :class="{ 'rotate-icon': showPatientSelector }"
                style="margin-left: 6px;"
            />
          </div>

          <!-- 可展开的就诊人选择器，带从上往下的动画 -->
          <transition name="slide-down">
            <div class="patient-switcher" v-show="showPatientSelector">
              <div class="switcher-header">
                <div class="switcher-title">选择就诊人</div>
                <div v-if="showScrollIndicator" class="scroll-indicator">
                  <van-icon name="arrow-left-right" size="14px" color="#999" />
                  <span class="indicator-text">滑动查看更多</span>
                </div>
              </div>

              <div
                  class="patient-scroll"
                  ref="patientScroll"
                  @scroll="handleScroll"
              >
                <div
                    class="patient-item"
                    v-for="(patient, index) in manageablePatients"
                    :key="patient.id"
                    @click="switchPatient(patient, index)"
                    :class="{ 'active': patient.id === currentPatient.id }"
                    :ref="el => patientRefs[index] = el"
                >
                  <div class="patient-avatar">
                    <van-icon
                        name="user-o"
                        :color="patient.id === currentPatient.id ? '#fff' : '#1989fa'"
                        :size="24"
                    />
                  </div>
                  <div class="patient-info">
                    <div class="patient-name">{{ patient.name }}</div>
                    <div class="patient-relation">{{ patient.relation }}</div>
                  </div>
                </div>
              </div>
            </div>
          </transition>

          <!-- 健康档案卡片（有数据时） -->
          <div v-if="currentHealthProfile" class="profile-card">
            <!-- 基础信息分组 -->
            <div class="profile-section">
              <h3 class="section-title">基础信息</h3>
              <van-cell-group class="detail-cell-group">
                <van-cell title="姓名" :value="currentHealthProfile.name || '未填写'" label-position="left"/>
                <van-cell title="性别" :value="currentHealthProfile.gender || '未填写'" label-position="left"/>
                <van-cell title="年龄" :value="currentHealthProfile.age ? `${currentHealthProfile.age}岁` : '未填写'" label-position="left"/>
                <van-cell title="血型" :value="currentHealthProfile.blood_type || '未填写'" label-position="left"/>
                <van-cell title="联系电话" :value="currentHealthProfile.phone || '未填写'" label-position="left"/>
              </van-cell-group>
            </div>

            <!-- 身体指标分组 -->
            <div class="profile-section">
              <h3 class="section-title">身体指标</h3>
              <van-cell-group class="detail-cell-group">
                <van-cell title="身高" :value="currentHealthProfile.height ? `${currentHealthProfile.height}cm` : '未填写'" label-position="left"/>
                <van-cell title="体重" :value="currentHealthProfile.weight ? `${currentHealthProfile.weight}kg` : '未填写'" label-position="left"/>
                <van-cell
                    title="BMI"
                    :value="computedBmi ? `${computedBmi.toFixed(1)} (${getBmiDesc(computedBmi)})` : '未填写'"
                    label-position="left"
                />
              </van-cell-group>
            </div>
          </div>

          <!-- 空状态（无数据时） -->
          <div v-else class="empty-tip">
            暂无健康档案<br/>
            <span style="font-size:12px;color:#999;">可前往体检后完善档案</span>
          </div>
        </div>
      </van-tab>

      <!-- 就诊记录标签页 -->
      <van-tab title="就诊记录">
        <div class="scroll-container">
          <div class="records-list">
            <div class="record-item" v-for="record in medicalRecords" :key="record.order_id">
              <div class="date-box">{{ record.visit_date }}</div>
              <div class="record-details">
                <div class="department">{{ record.dept_name }}</div>
                <div class="diagnosis">{{ record.chief_complaint }}</div>
                <div class="patient-name">就诊人：{{ record.patient_name }}</div>
              </div>
              <van-icon name="arrow" class="arrow-icon" @click="showRecordDetail(record)"/>
            </div>
            <div v-if="medicalRecords.length === 0" class="empty-tip">
              暂无就诊记录
            </div>
          </div>
        </div>
      </van-tab>

      <!-- 健康提醒标签页 -->
      <van-tab title="健康提醒">
        <div class="scroll-container">
          <van-notice-bar
              left-icon="volume-o"
              background="#ecf9ff"
              color="#1989fa"
              :text="reminders[0]?.content || '暂无健康提醒'"
          />
          <div class="reminders-section">
            <div class="reminder-card" v-for="reminder in reminders" :key="reminder.id">
              <div class="reminder-header">
                <van-icon name="bell" size="20px" color="#ee0a24" />
                <span class="reminder-title">{{ reminder.title }}</span>
              </div>
              <div class="reminder-content">
                <div class="reminder-detail">
                  <van-icon name="clock-o" size="14px" />
                  <span>{{ reminder.time }}</span>
                </div>
                <div class="reminder-detail">
                  <van-icon name="description" size="14px" />
                  <span>{{ reminder.content }}</span>
                </div>
                <div class="reminder-detail">
                  <van-icon name="user-o" size="14px" />
                  <span>提醒对象：{{ reminder.patient_name }}</span>
                </div>
              </div>
            </div>
            <div v-if="reminders.length === 0" class="empty-tip">
              暂无健康提醒
            </div>
          </div>
        </div>
      </van-tab>
    </van-tabs>

    <!-- 就诊记录详情弹窗 -->
    <van-popup
        v-model:show="showRecordDetailPopup"
        position="bottom"
        class="record-detail-popup"
        :style="{ height: 'auto', maxHeight: '80%', borderRadius: '16px 16px 0 0', background: '#fff' }"
        :z-index="2000"
    >
      <div class="dialog-header">
        <h3 class="dialog-title">就诊记录详情</h3>
        <van-icon name="close" @click="showRecordDetailPopup = false" class="close-icon" />
      </div>
      <van-cell-group class="detail-cell-group">
        <van-cell title="就诊人" :value="currentRecord?.patient_name || '未填写'" label-position="left"/>
        <van-cell title="就诊日期" :value="currentRecord?.visit_date || '未填写'" label-position="left"/>
        <van-cell title="就诊科室" :value="currentRecord?.dept_name || '未填写'" label-position="left"/>
        <van-cell title="就诊医生" :value="currentRecord?.doctor_name || '未填写'" label-position="left"/>
        <van-cell title="患者主要症状" :value="currentRecord?.chief_complaint || '未填写'" label-position="left"/>
        <van-cell title="诊断结果" :value="currentRecord?.diagnosis || '未填写'" label-position="left"/>
      </van-cell-group>
      <div class="dialog-footer">
        <van-button block type="primary" @click="showRecordDetailPopup = false">关闭</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, getCurrentInstance, nextTick, watch } from 'vue';
import { useUserStore } from "../stores/user.js";
import { showToast } from "vant";


const { proxy } = getCurrentInstance();
const userStore = useUserStore();

// 返回上一页功能
// const handleGoBack = () => {
//   if (proxy && proxy.$router) {
//     proxy.$router.back();
//   } else {
//     window.history.back();
//   }
// };

// 状态管理
const activeTab = ref(0);

// 就诊记录详情相关状态
const showRecordDetailPopup = ref(false);
const currentRecord = ref(null);

// 就诊人列表（初始为空，等待接口数据）
const manageablePatients = ref([]);

const profilesObj = {};

const genderMap={
  0:'未知',
  1:'男',
  2:'女'
}

const managePatient = () => {
  proxy.$axios.get('/api/v1/patient',{params:{user_id:userStore.userInfo.user_id}})
      .then((serverData)=>{
        if(serverData.data.code == 0){
          // 转换接口数据格式
          const transformData = serverData.data.data.map((item)=>{
            return{
              id: item.patient_id,
              name: item.name,
              relation: item.relationship,
            }
          });
          manageablePatients.value = transformData;

          // 缓存健康档案数据
          serverData.data.data.forEach((item)=>{
            profilesObj[item.patient_id] = {
              name: item.name,
              gender: genderMap[item.gender],
              age: calculateAge(item.birth_date),
              blood_type: item.blood_type,
              phone: item.phone,
              height: item.height,
              weight: item.weight,
            };
          });


          // 设置默认就诊人为第一个元素，如果存在的话
          if (manageablePatients.value.length > 0) {
            // 优先查找姓名为"张三"的就诊人
            const zhangsan = manageablePatients.value.find(p => p.name === '张三');
            currentPatient.value = zhangsan || manageablePatients.value[0];
            getHealthProfileByPatient(currentPatient.value.id);
          }
        }
      });
};

// 当前就诊人（初始为空，等待接口数据）
const currentPatient = ref({});
const currentHealthProfile = ref(null);

// 出生日期转换为年龄的函数
const calculateAge = (birthDateStr) => {
  if (!birthDateStr) return null; // 处理空值

  // 解析出生日期（假设格式为 'YYYY-MM-DD'）
  const birthDate = new Date(birthDateStr);
  const today = new Date();

  // 验证日期有效性
  if (isNaN(birthDate.getTime())) {
    console.error('无效的出生日期格式:', birthDateStr);
    return null;
  }

  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();

  // 如果当前月份小于出生月份，或者月份相同但日期未到，年龄减1
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }

  return age > 0 ? age : 0; // 确保年龄不为负数
};

// 就诊人选择器显示/隐藏状态
const showPatientSelector = ref(false);

// 切换选择器显示状态
const toggleSelector = () => {
  showPatientSelector.value = !showPatientSelector.value;
};

// 滚动相关引用和状态
const patientScroll = ref(null);
const patientRefs = ref([]);
const showScrollIndicator = ref(false);
const scrollIndicatorTimeout = ref(null);

// 检查是否需要显示滚动指示器
const checkScrollable = () => {
  nextTick(() => {
    if (patientScroll.value) {
      const { scrollWidth, clientWidth } = patientScroll.value;
      showScrollIndicator.value = scrollWidth > clientWidth + 10; // 有多余内容时显示

      // 自动隐藏指示器
      if (scrollIndicatorTimeout.value) {
        clearTimeout(scrollIndicatorTimeout.value);
      }
      scrollIndicatorTimeout.value = setTimeout(() => {
        showScrollIndicator.value = false;
      }, 3000);
    }
  });
};

// 处理滚动事件
const handleScroll = () => {
  if (showScrollIndicator.value) {
    // 滚动时重置指示器隐藏时间
    if (scrollIndicatorTimeout.value) {
      clearTimeout(scrollIndicatorTimeout.value);
    }
    scrollIndicatorTimeout.value = setTimeout(() => {
      showScrollIndicator.value = false;
    }, 1500);
  }
};

// 切换就诊人 - 选择后自动收起选择器
const switchPatient = (patient, index) => {
  // 添加切换动画效果
  if (patientRefs.value[index]) {
    patientRefs.value[index].classList.add('switching');
    setTimeout(() => {
      patientRefs.value[index].classList.remove('switching');
    }, 300);
  }

  currentPatient.value = patient;
  getHealthProfileByPatient(patient.id);

  // 选择后自动收起选择器
  showPatientSelector.value = false;

  // 自动滚动到选中项，使其居中显示
  nextTick(() => {
    if (patientScroll.value && patientRefs.value[index]) {
      const scrollContainer = patientScroll.value;
      const item = patientRefs.value[index];

      // 计算滚动位置，使选中项居中
      const containerRect = scrollContainer.getBoundingClientRect();
      const itemRect = item.getBoundingClientRect();
      const scrollPosition = itemRect.left - containerRect.left + scrollContainer.scrollLeft - (containerRect.width / 2 - itemRect.width / 2);

      // 平滑滚动
      scrollContainer.scrollTo({
        left: scrollPosition,
        behavior: 'smooth'
      });
    }
  });
};

// 根据当前就诊人获取健康档案
const getHealthProfileByPatient = (patientId) => {
  currentHealthProfile.value = profilesObj[patientId];
};

// 计算BMI指数
const computedBmi = computed(() => {
  if (!currentHealthProfile.value || !currentHealthProfile.value.height || !currentHealthProfile.value.weight) {
    return null;
  }

  const height = parseFloat(currentHealthProfile.value.height) / 100; // 转换为米
  const weight = parseFloat(currentHealthProfile.value.weight);

  if (height <= 0) return null;

  return weight / (height * height);
});

// 就诊记录数据
const medicalRecords = ref([]);

// 获取就诊记录数据
const medicalRecord = () => {
  if (proxy && proxy.$axios) {
    proxy.$axios.get("/api/v1/getMedicalRecords", { params: { user_id: userStore.userInfo.user_id } })
        .then((serverData) => {
          if (serverData.data.code == 0) {
            medicalRecords.value = serverData.data.data;
          } else {
            showToast(serverData.data.message);
          }
        });
  }
};

// 健康提醒数据
const reminders = ref([]);

let healthReminder = ref([]);
const frontData = computed(() => {
  return healthReminder.value.map(item => {
    return {
      id: item.id,
      title: item.remind_type,
      content: item.content,
      patient_name: item.patient_name,
      time: formatTime(item)
    };
  });
});

// 获取健康提醒数据
const selecthealthReminder = () => {
  if (proxy && proxy.$axios) {
    proxy.$axios.get("/api/v1/healthReminder", { params: { user_id: userStore.userInfo.user_id } })
        .then((serverData) => {
          if (serverData.data.code == 0) {
            healthReminder.value = serverData.data.data;
            reminders.value = frontData.value;
          } else {
            showToast('获取数据失败');
          }
        });
  }
};

// BMI描述计算
const getBmiDesc = (bmi) => {
  const bmiValue = parseFloat(bmi);
  if (bmiValue < 18.5) return '偏瘦';
  if (bmiValue < 24) return '正常';
  if (bmiValue < 28) return '超重';
  return '肥胖';
};

// 显示就诊记录详情
const showRecordDetail = (record) => {
  currentRecord.value = record;
  showRecordDetailPopup.value = true;
};

// 格式化时间
const formatTime = (row) => {
  const { repeat_strategy, once_datetime, daily_time } = row;
  if (repeat_strategy === 'once') {
    return once_datetime?.slice(0, 16) || '';
  } else if (repeat_strategy === 'daily') {
    return `每日${daily_time?.slice(0, 5) || ''}`;
  }
  return '';
};

// 动态调整内容区域样式
const adjustContentPadding = () => {
  nextTick(() => {
    const contentArea = document.querySelector('.van-tabs__content');
    if (contentArea) {
      contentArea.style.paddingBottom = '20px';
    }
  });
};

// 监听窗口大小变化，重新检查滚动状态
const handleResize = () => {
  checkScrollable();
  adjustContentPadding();
};

// 生命周期初始化
onMounted(() => {
  medicalRecord();
  selecthealthReminder();
  managePatient();
  checkScrollable();
  adjustContentPadding();

  window.addEventListener('resize', handleResize);
});

// 监听就诊人数据变化，重新检查滚动状态
watch(manageablePatients, () => {
  checkScrollable();
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (scrollIndicatorTimeout.value) {
    clearTimeout(scrollIndicatorTimeout.value);
  }
});
</script>

<style scoped>
/* 基础布局 */
.hospital-system {
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  min-height: 100vh;
  position: relative;
}

/* 滚动容器通用样式 */
.scroll-container {
  height: calc(100vh - 140px);
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding: 16px;
  box-sizing: border-box;
}

/* 就诊人选择器展开/收起动画 */
.slide-down-enter-from, .slide-down-leave-to {
  max-height: 0;
  opacity: 0;
  transform: translateY(-10px);
}
.slide-down-enter-to, .slide-down-leave-from {
  max-height: 200px;
  opacity: 1;
  transform: translateY(0);
}
.slide-down-enter-active, .slide-down-leave-active {
  transition: all 0.3s cubic-bezier(0.68, -0.55, 0.27, 1.55);
  overflow: hidden;
}

/* 选择器触发按钮 */
.selector-trigger {
  padding: 14px 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  font-size: 16px;
  color: #1989fa;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-bottom: 12px;
  transition: transform 0.2s, box-shadow 0.2s;
}
.selector-trigger:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(25, 137, 250, 0.15);
}
.rotate-icon {
  transform: rotate(180deg);
  transition: transform 0.3s;
}

/* 就诊人切换器样式 */
.patient-switcher {
  margin-bottom: 16px;
  background: white;
  border-radius: 8px;
  padding: 12px 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.switcher-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.switcher-title {
  font-size: 14px;
  color: #666;
  padding-left: 4px;
}

/* 滚动指示器 */
.scroll-indicator {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
  animation: fadeIn 0.5s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.indicator-text {
  margin-left: 4px;
}

.patient-scroll {
  display: flex;
  gap: 12px;
  overflow-x: auto;
  padding: 4px 0;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none; /* 隐藏滚动条 */
  scroll-behavior: smooth; /* 平滑滚动 */
}

.patient-scroll::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}

.patient-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 90px;
  padding: 12px 8px;
  border-radius: 10px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
}

.patient-item.active {
  background: #1989fa;
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
}

.patient-item.switching {
  animation: pulse 0.3s ease;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.patient-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  background: #f0f7ff;
}

.patient-item.active .patient-avatar {
  background: rgba(255, 255, 255, 0.2);
}

.patient-name {
  font-size: 15px;
  font-weight: 500;
  text-align: center;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80px;
}

.patient-relation {
  font-size: 12px;
  color: #888;
  text-align: center;
  white-space: nowrap;
}

.patient-item.active .patient-relation {
  color: rgba(255, 255, 255, 0.8);
}

/* 顶部导航栏样式 */
.van-nav-bar {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 101 !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.van-nav-bar__title, .van-nav-bar__left {
  color: white !important;
}

/* 空状态提示 */
.empty-tip {
  text-align: center;
  padding: 40px 0;
  color: #999;
  font-size: 14px;
  line-height: 1.6;
}

/* 健康档案卡片样式 */
.profile-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.profile-section {
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
}
.profile-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
  padding-left: 4px;
  border-left: 3px solid #1989fa;
}

/* 就诊记录相关样式 */
.records-list {
  margin: 0;
}
.record-item {
  display: flex;
  align-items: center;
  background: white;
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
}
.record-item:hover {
  transform: translateX(4px);
}
.date-box {
  width: 80px;
  padding: 6px 0;
  background: #e6f7ff;
  color: #1890ff;
  border-radius: 4px;
  text-align: center;
  font-weight: bold;
  margin-right: 16px;
  flex-shrink: 0;
}
.record-details {
  flex: 1;
}
.department {
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}
.diagnosis {
  font-size: 14px;
  color: #666;
}
.record-details .patient-name {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
.arrow-icon {
  color: #1989fa;
  font-size: 18px;
  cursor: pointer;
  padding: 8px;
  transition: transform 0.2s;
}
.arrow-icon:hover {
  transform: scale(1.1);
}

/* 健康提醒相关样式 */
.reminders-section {
  margin: 0;
}
.reminder-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border-left: 3px solid #ee0a24;
}
.reminder-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.reminder-title {
  font-weight: bold;
  color: #333;
  margin-left: 8px;
}
.reminder-content {
  padding-left: 28px;
}
.reminder-detail {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}
.reminder-detail .van-icon {
  margin-right: 8px;
  margin-top: 2px;
  flex-shrink: 0;
}

/* 弹窗样式 */
.record-detail-popup, .van-popup {
  padding: 24px;
  box-sizing: border-box;
  width: 100%;
}
.dialog-header {
  margin-bottom: 20px;
  text-align: center;
  position: relative;
}
.close-icon {
  position: absolute;
  right: 12px;
  top: 8px;
  color: #999;
  font-size: 20px;
}
.dialog-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.detail-cell-group {
  margin-bottom: 24px;
}
.detail-cell-group .van-cell {
  background: transparent;
  padding: 12px 16px;
  border-bottom: 1px solid #f5f5f5;
}
.detail-cell-group .van-cell:last-child {
  border-bottom: none;
}
.detail-cell-group .van-cell__title {
  color: #666;
}
.detail-cell-group .van-cell__value {
  color: #333;
}

.dialog-footer {
  padding-top: 16px;
}
.dialog-footer .van-button {
  height: 44px;
  line-height: 44px;
  border-radius: 8px;
  background: linear-gradient(135deg, #1989fa, #3a8df8);
  border: none;
  color: white;
  font-weight: bold;
}

.van-popup, .van-dialog {
  z-index: 2000 !important;
}
</style>
